/*
 * @Author: Bernard liangyongkang@lspace.vip
 * @Date: 2024-04-09 20:13:41
 * @LastEditors: Bernard liangyongkang@lspace.vip
 * @LastEditTime: 2024-04-09 20:24:41
 * @FilePath: \graduation-design\server\app\controllers\app\auth.go
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
package app

import (
	"server/app/common/request"
	"server/app/common/response"
	"server/app/services"

	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
)

// 编写Login()，进行入参检验，并调用UserService和JwtService服务，颁发Token
func Login(ctx *gin.Context) {
	var form request.Login
	if err := ctx.ShouldBindJSON(&form); err != nil {
		response.ValidateFail(ctx, request.GetErrorMsg(form, err))
		return
	}
	if err, user := services.UserService.Login(form); err != nil {
		response.BusinessFail(ctx, err.Error())
	} else {
		tokenData, err, _ := services.JwtService.CreateToken(services.AppGuardName, user)
		if err != nil {
			response.BusinessFail(ctx, err.Error())
			return
		}
		response.Success(ctx, tokenData)
	}
}

func Info(ctx *gin.Context) {
	err, user := services.UserService.GetUserInfo(ctx.Keys["id"].(string))
	if err != nil {
		response.BusinessFail(ctx, err.Error())
		return
	}
	response.Success(ctx, user)
}

// 用户登出
func Logout(ctx *gin.Context) {
	err := services.JwtService.JoinBlackList(ctx.Keys["token"].(*jwt.Token))
	if err != nil {
		response.BusinessFail(ctx, "登出失败")
		return
	}
	response.Success(ctx, nil)
}

// 用户信息设置
func SetInfo(ctx *gin.Context) {
	var form request.UserInfo
	if err := ctx.ShouldBindJSON(&form); err != nil {
		response.ValidateFail(ctx, request.GetErrorMsg(form, err))
		return
	}
	err := services.UserService.SetUserInfo(ctx.Keys["id"].(string), form)
	if err != nil {
		response.BusinessFail(ctx, "用户id错误")
		return
	}
	response.Success(ctx, nil)
}
